package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.util.ConstantPropertiesUtils;
import com.atguigu.yygh.order.util.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName WeixinServiceImpl
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-10-21 20:09
 * @Version 1.0
 */
@Service
public class WeixinServiceImpl implements WeixinService {
    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    @Override
    public Map createNative(Long orderId) {

        try {
            //1. 检查redis中是否存在该订单的支付链接
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (payMap != null) {
                return payMap;
            }
            //2. 根据id获取订单信息
            OrderInfo order = orderService.getById(orderId);
            //3. 保存交易记录
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            //4 调用微信统一下单接口
            //4.1 封装参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众账号id
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);//商户号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串 32为以内
            Date reserveDate = order.getReserveDate();//安排日期
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊" + order.getDepname(); // 2022/10/22 就诊 多发性硬化专科门诊
            paramMap.put("body",body);//商品描述
            paramMap.put("out_trade_no",order.getOutTradeNo());
            paramMap.put("total_fee","1");//订单总金额,测试1分钱
            paramMap.put("spbill_create_ip","127.0.0.1");
            paramMap.put("notify_url","http://guli.shop/api/order/weixinPay/weixinNotify");//没有
            paramMap.put("trade_type","NATIVE");

            //4.2 HTTPClient调用统一下单接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //4.3 返回第三方的数据
            String xml = client.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            //5. 封装返回结果集
            Map map = new HashMap();
            map.put("orderId",orderId);
            map.put("totalFee",order.getAmount());
            map.put("resultCode",resultMap.get("result_code"));//SUCCESS/FAIL
            map.put("codeUrl",resultMap.get("code_url"));//二维码链接
            //6. 存入redis五分钟
            redisTemplate.opsForValue().set(orderId.toString(),map,5, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }
    }

    @Override
    public Map queryPayStatus(Long orderId) {

        try {
            OrderInfo orderInfo = orderService.getById(orderId);
            //1. 封装参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众账号id
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);//商户号
            paramMap.put("out_trade_no",orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串 32为以内

            //2 设置请求--调用微信 查询下单接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //3. 返回第三方的数据,转成Map
            String xml = client.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            //4. 返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Boolean refund(Long orderId) {
        try {
            //1. 查询支付记录
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //2. 根据支付记录创建退款记录
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfoQuery);
            //3. 判断退款状态--是否已退款REFUND
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
                return true;
            }
            //4. 封装退款参数
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众账号id
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);//商户号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串 32为以内
            paramMap.put("transaction_id",paymentInfoQuery.getTradeNo());//微信订单号
            paramMap.put("out_trade_no",paymentInfoQuery.getOutTradeNo());//商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfoQuery.getOutTradeNo());//商户退款编号
            paramMap.put("total_fee","1");//订单金额
            paramMap.put("refund_fee","1");//退款金额

            //5. 调用微信退款接口
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            //6. 微信返回参数
            String xml = client.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            //7. 更新退款记录状态REFUND
            if (resultMap != null && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                refundInfo.setTradeNo(resultMap.get("refund_id"));//微信退款单号
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackTime(new Date());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
            }

        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
